<template>
  <el-row :gutter="20">
    <el-col :span="4" :xs="24">
      <ContentWrap class="h-full">
        <DeptTree ref="deptTreeRef" @node-click="handleDeptNodeClick" />
      </ContentWrap>
    </el-col>
    <el-col :span="20" :xs="24">
      <!-- 搜索区域 -->
      <ContentWrap>
        <ElForm
          class="-mb-15px"
          :model="queryParams"
          ref="queryFormRef"
          :inline="true"
          label-width="68px"
        >
          <el-form-item label="用户编号" prop="staffId">
            <el-input
              v-model="queryParams.staffId"
              placeholder="请输入用户编号"
              clearable
              @keyup.enter="handleQuery"
              class="!w-240px"
            />
          </el-form-item>
          <el-form-item label="用户账号" prop="loginName">
            <el-input
              v-model="queryParams.loginName"
              placeholder="请输入用户账号"
              clearable
              @keyup.enter="handleQuery"
              class="!w-240px"
            />
          </el-form-item>
          <el-form-item label="手机号码" prop="mobile">
            <el-input
              v-model="queryParams.mobile"
              placeholder="请输入手机号码"
              clearable
              @keyup.enter="handleQuery"
              class="!w-240px"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select
              v-model="queryParams.status"
              placeholder="请选择状态"
              clearable
              class="!w-240px"
            >
              <el-option
                v-for="dict in common_enable_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="创建时间" prop="createTime">
            <el-date-picker
              v-model="queryParams.createTime"
              :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
              class="!w-240px"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              type="daterange"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item>
            <el-button @click="handleQuery">
              <Icon icon="ep:search" />
              搜索
            </el-button>
            <el-button @click="resetQuery">
              <Icon icon="ep:refresh" />
              重置
            </el-button>
            <el-button
              type="primary"
              plain
              @click="openForm('create')"
              v-hasPermi="['system:staff:create']"
            >
              <Icon icon="ep:plus" />
              新增
            </el-button>
            <el-button
              type="warning"
              plain
              @click="handleImport"
              v-hasPermi="['system:staff:import']"
            >
              <Icon icon="ep:upload" />
              导入
            </el-button>
            <el-button
              type="success"
              plain
              @click="handleExport"
              :loading="exportLoading"
              v-hasPermi="['system:staff:export']"
            >
              <Icon icon="ep:download" />
              导出
            </el-button>
          </el-form-item>
        </ElForm>
      </ContentWrap>

      <!-- 列表区域 -->
      <ContentWrap>
        <el-table v-loading="listLoading" :data="list">
          <el-table-column label="用户编号" prop="staffId" min-width="130" show-overflow-tooltip />
          <el-table-column label="用户账号" prop="loginName" show-overflow-tooltip />
          <el-table-column label="用户昵称" prop="nickname" show-overflow-tooltip />
          <el-table-column label="部门" prop="deptName" show-overflow-tooltip />
          <el-table-column label="手机号码" prop="mobile" width="120" />
          <el-table-column label="状态" prop="status">
            <template #default="scope">
              <el-switch
                v-model="scope.row.status"
                :active-value="EnableStatusEnum.Enabled"
                :inactive-value="EnableStatusEnum.Disabled"
                @change="handleStatusChange(scope.row)"
                :disabled="!hasPermi('system:staff:update') || !getIsOperatable(scope.row, false)"
              />
            </template>
          </el-table-column>
          <el-table-column label="创建时间" prop="createTime" width="180" />
          <el-table-column label="操作">
            <template #default="scope">
              <!--              <div class="flex items-center justify-center">-->
              <div
                class="flex items-center"
              >
                <el-button
                  type="primary"
                  link
                  @click="openForm('update', scope.row.staffId)"
                  v-hasPermi="['system:staff:update']"
                  v-if="getIsOperatable(scope.row, true)"
                >
                  <!--                  <Icon icon="ep:edit" />-->
                  编辑
                </el-button>
                <el-dropdown
                  @command="(command) => handleCommand(command, scope.row)"
                  v-hasPermi="[
                    'system:staff:delete',
                    'system:staff:update-password',
                    'system:permission:assign-user-role'
                  ]"
                  v-if="getIsOperatable(scope.row, false)"
                >
                  <el-button type="primary" link>
                    <Icon icon="ep:d-arrow-right" />
                    更多
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <!--
                        这里使用v-hasPermi会报以下警告，改用v-if方式：
                        [Vue warn]: Runtime directive used on component with non-element root node. The directives will not function as intended.
                      -->
                      <el-dropdown-item
                        command="handleDelete"
                        v-if="hasPermi('system:staff:delete')"
                      >
                        <Icon icon="ep:delete" />
                        删除
                      </el-dropdown-item>
                      <el-dropdown-item
                        command="handleUpdatePasswd"
                        v-if="hasPermi('system:staff:update-password')"
                      >
                        <Icon icon="ep:key" />
                        重置密码
                      </el-dropdown-item>
                      <el-dropdown-item
                        command="handleAssignRole"
                        v-if="hasPermi('system:permission:assign-user-role')"
                      >
                        <Icon icon="ep:circle-check" />
                        分配角色
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <Pagination
          :total="total"
          v-model:page="queryParams.pageNo"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </ContentWrap>
    </el-col>
  </el-row>

  <!-- 表单弹窗：添加/修改 -->
  <StaffForm ref="editFormRef" @success="getList" />
  <!-- 用户导入弹框 -->
  <StaffImportForm ref="importFormRef" @success="getList" />
  <!-- 分配角色弹框 -->
  <StaffAssignRoleForm ref="assignRoleFormRef" @success="getList" />
</template>

<script setup lang="ts">
import * as StaffApi from '@/api/system/staff'
import { hasPermi } from '@/utils/perm'
import {EnableStatusEnum, SystemRoleCodeEnum} from '@/utils/constants'
import DeptTree from './DeptTree.vue'
import StaffForm from './StaffForm.vue'
import StaffImportForm from './StaffImportForm.vue'
import StaffAssignRoleForm from './StaffAssignRoleForm.vue'
import download from '@/utils/download'
import {useUserStore} from "@/stores/modules/user";

defineOptions({ name: 'SystemStaff' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const userStore = useUserStore()
const { common_enable_status } = useIntDict(DICT_TYPE.common_enable_status)

const queryParams = reactive({
  staffId: undefined,
  loginName: undefined,
  nickname: undefined,
  mobile: undefined,
  deptId: undefined,
  status: undefined,
  createTime: [],
  pageNo: 1,
  pageSize: 10
})
const queryFormRef = ref()

const listLoading = ref(false)
const exportLoading = ref(false)

const list = ref([]) // 列表数据
const total = ref(0) // 列表数据总条数

const getList = async () => {
  listLoading.value = true
  try {
    const data = await StaffApi.getStaffPage(queryParams)
    list.value = data.content
    total.value = data.totalElement
  } finally {
    listLoading.value = false
  }
}

const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

const resetQuery = () => {
  queryFormRef.value.resetFields()
  queryParams.deptId = undefined
  unselectDeptTree()
  handleQuery()
}

/**
 * 用户数据是否可操作
 * @param row
 * @param allowSelf 若是当前登录用户自身数据，是否可操作
 */
const getIsOperatable = (row: StaffApi.StaffVO, allowSelf: boolean) => {
  if (allowSelf && userStore.getUser?.userId === row.staffId) {
    return true
  }
  return !(row.roles ?? []).some((role) => [SystemRoleCodeEnum.Super_Admin, SystemRoleCodeEnum.Tenant_Admin].includes(role.code))
}

const handleCommand = (command: string, row: StaffApi.StaffVO) => {
  switch (command) {
    case 'handleDelete':
      handleDelete(row.staffId!)
      break
    case 'handleUpdatePasswd':
      handleUpdatePasswd(row)
      break
    case 'handleAssignRole':
      handleAssignRole(row)
      break
    default:
      break
  }
}

const handleDelete = async (staffId: string) => {
  try {
    // 弹出确认框
    await message.delConfirm()
    // 发起删除请求
    await StaffApi.deleteStaff(staffId)
    // 成功提示
    message.success(t('common.delSuccess'))
    // 刷新列表(页码不变)
    await getList()
  } catch {}
}

const importFormRef = ref<InstanceType<typeof StaffImportForm>>()
const handleImport = () => {
  importFormRef.value?.open()
}

const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await StaffApi.exportStaff(queryParams)
    download.excel(data, '用户数据.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

const handleUpdatePasswd = async (row: StaffApi.StaffVO) => {
  try {
    // 二次确认
    const result = await message.prompt(`请输入"${row.loginName}"的新密码`)
    await StaffApi.updateStaffPasswd(row.staffId!, result.value)
    message.success(t('common.updateSuccess'))
  } catch {}
}

const handleStatusChange = async (row: StaffApi.StaffVO) => {
  try {
    // 修改状态的二次确认
    // 状态已是switch切换后的值
    const text = row.status === EnableStatusEnum.Enabled ? '启用' : '停用'
    await message.confirm(`确认要"${text}""${row.loginName}"用户吗?`)
    await StaffApi.updateStaffStatus(row.staffId!, row.status)
    // await getList()  // 暂不做刷新
    message.success(`${text}成功`)
  } catch {
    row.status =
      row.status === EnableStatusEnum.Enabled ? EnableStatusEnum.Disabled : EnableStatusEnum.Enabled
  }
}

const deptTreeRef = ref<InstanceType<typeof DeptTree>>()
const unselectDeptTree = () => {
  deptTreeRef.value?.unselect()
}

const editFormRef = ref<InstanceType<typeof StaffForm>>()
const openForm = (type: string, staffId?: string) => {
  editFormRef.value?.open(type, staffId)
}

const assignRoleFormRef = ref<InstanceType<typeof StaffAssignRoleForm>>()
const handleAssignRole = (row: StaffApi.StaffVO) => {
  assignRoleFormRef.value?.open(row)
}

const handleDeptNodeClick = async (node) => {
  queryParams.deptId = node.id
  await getList()
}

onMounted(() => {
  getList()
})
</script>

<style scoped lang="scss"></style>
